import { useState, useEffect } from 'react';
import { Tree, Input, Table, Button, Popconfirm, Message, Form, Modal, Select, Checkbox } from '@arco-design/web-react';
import { IconPlus } from '@arco-design/web-react/icon';
import './Power.css'
// import http from '../../utils/http';
import systemApi from '../../API/systemApi';
import useForm from '@arco-design/web-react/es/Form/useForm';
const TreeNode = Tree.Node;
const CheckboxGroup = Checkbox.Group;
//修改
const FormItem = Form.Item
//树的初始值
const TreeData = [
    {
        title: 'Trunk 1',
        key: '0-0',
        children: [
            {
                title: 'Trunk 1-0',
                key: '0-0-0',
                children: [
                    {
                        title: 'leaf',
                        key: '0-0-0-0',
                    },
                    {
                        title: 'leaf',
                        key: '0-0-0-1',
                        children: [
                            {
                                title: 'leaf',
                                key: '0-0-0-1-0',
                            },
                        ],
                    },
                    {
                        title: 'leaf',
                        key: '0-0-0-2',
                    },
                ],
            },
            {
                title: 'Trunk 1-1',
                key: '0-0-1',
            },
            {
                title: 'Trunk 1-2',
                key: '0-0-2',
                children: [
                    {
                        title: 'leaf',
                        key: '0-0-2-0',
                    },
                    {
                        title: 'leaf',
                        key: '0-0-2-1',
                    },
                ],
            },
        ],
    },
    {
        title: 'Trunk 2',
        key: '0-1',
    },
    {
        title: 'Trunk 3',
        key: '0-2',
        children: [
            {
                title: 'Trunk 3-0',
                key: '0-2-0',
                children: [
                    {
                        title: 'leaf',
                        key: '0-2-0-0',
                    },
                    {
                        title: 'leaf',
                        key: '0-2-0-1',
                    },
                ],
            },
        ],
    },
];

function searchData(inputValue) {
    const loop = (data) => {
        const result = [];
        data.forEach((item) => {
            if (item.title.toLowerCase().indexOf(inputValue.toLowerCase()) > -1) {
                result.push({ ...item });
            } else if (item.children) {
                const filterData = loop(item.children);

                if (filterData.length) {
                    result.push({ ...item, children: filterData });
                }
            }
        });
        return result;
    };

    return loop(TreeData);
}

const Power = () => {
    //树的值
    const [treeData, setTreeData] = useState([
        {
            title: '停车场管理员',
            key: '停车场管理员',
            children: []
        },
        {
            title: '超级管理员',
            key: '超级管理员',
            children: []
        },
        {
            title: '运维人员',
            key: '运维人员',
             children: []
        },
        {
            title: '运营人员',
            key: '运营人员',
            children: []
        },
        {
            title: '收费员',
            key: '收费员',
            children: []
        },
        {
            title: '测试权限',
            key: '测试权限',
            children: []
        },
    ]);
      //树的请求
      const aa = (a, b) => {
        console.log(a);
        // console.log(a, b.node.props.dataRef.children);
        // eslint-disable-next-line no-self-compare
        if (a[0] === a[0] && treeData[0].children.length === 0) {
            let arr = [...treeData]
            systemApi.getTree(a[0]).then((res) => {
                // console.log(res);
                res.result.map((item) => {
                    arr[0].children.push({
                        title: item.userName,
                        key: item.userId,
                        ...item
                    })
                })
                setTreeData(arr)
                // console.log(arr);
                setData(b.node.props.dataRef.children)
            })
        }
    }
    // 收索框的值
    const [inputValue, setInputValue] = useState('');
    //查找
    const querry = () => {
        console.log(inputValue);
        if (inputValue.length > 0) {
            systemApi.power(inputValue).then((res) => {
                console.log(res);
                if (res.code === 200) {
                    // setTreeData(res.result)
                    setData(res.result)

                }
            })
        }

    }
    //表头
    const columns = [
        {
            title: '序号',
            render: (col, record, index) => `${index + 1}`,
            // render: (text, record, index) => `${index + 1}`,
            editable: true,
        },
        {
            title: '姓名',
            dataIndex: 'userName',
            editable: true,
        },
        {
            title: '所属角色',
            dataIndex: 'roleName',
        },
        {
            title: '手机号',
            dataIndex: 'userPhone',
        },
        {
            title: '电子邮箱',
            dataIndex: 'userMail',
        },
        {
            title: '最近登录时间',
            dataIndex: 'userLastLoginTime',
        },
        {
            title: '操作',
            dataIndex: 'op',
            render: (col, record) => (
                <>
                    <Button style={{ backgrount: 'white' }} onClick={() => modify(record)} type='text'>
                        修改
                    </Button>

                    <Popconfirm
                        title='你确定要删除这条数据?'
                        onOk={() => { remove(record.userId) }}
                    >
                        <Button type='text'>
                            删除
                        </Button>
                    </Popconfirm>
                </>
            ),
        },
    ];

    //表格的值
    const [data, setData] = useState([])
    //表格的请求
    useEffect(() => {
        dataShow()
    }, [])
    const dataShow = () => {
        systemApi.getAdmin().then((res) => {
            if (res.code === 200) {
                let dataValue = res.result
                setData(dataValue)
                // setTreeData(dataValue)
            }

        })
        // http({
        //     url: '/system/AdminPower/getAllAdminInfo',
        //     method: 'get'
        // }).then((res) => {
        //     console.log(res);
        //     let dataValue = res.result
        //     setData(dataValue)

        // })
    }
    //
    //删除

    const remove = (id) => {
        systemApi.deleteData(id).then((res) => {
            if (res.code === 200) {
                dataShow()
                Message.success('删除成功')
            }
        })



    }


    //分页器

    //翻页
    const [loading, setLoading] = useState(false);

    //修改弹窗的配置
    const [visible, setVisible] = useState(false);
    const [form] = Form.useForm();
    //弹窗回显
    function modify(record) {
        setVisible(true);
        // console.log(record);
        form.setFieldsValue(record)
    }
    // 确定按钮
    function modifyBtn() {
        let value = form.getFieldsValue()
        //   console.log(value);
        systemApi.revise(value).then((res) => {
            console.log(res);
            if (res.code === 200) {
                dataShow()
                setVisible(false);
                Message.info({
                    content: '修改成功',
                });


            }
        })

    }
    //角色下拉框
    const [roleValue, setRoleValue] = useState()
    const roleDown = () => {
        systemApi.roleDown().then((res) => {
            let roleArr = [];
            for (let i = 0; i < res.result.length; i++) {

                roleArr.push({
                    label: res.result[i].roleName,
                    value: res.result[i].roleName
                })
            }
            setRoleValue(roleArr)
        })
        // http({
        //     url: '/system/AdminPower/getAllRole',
        //     method: 'get'
        // }).then((res) => {
        //     console.log(res);
        //     let roleArr = [];
        //     for (let i = 0; i < res.result.length; i++) {

        //         roleArr.push({
        //             label: res.result[i].roleName,
        //             value: res.result[i].roleName
        //         })
        //     }
        //     setRoleValue(roleArr)
        // })
    }
    //增加弹窗
    const [formAdd] = Form.useForm()
    const [addVisible, setaddVisible] = useState(false);

    const addBox = () => {
        let value = formAdd.getFieldsValue()
        console.log(value);
        systemApi.addAdmin(value).then((res) => {
            console.log(res);
            if (res.code === 200) {
                dataShow()
                setaddVisible(false)
                Message.success('添加成功')
            }
        })
    }
    //添加角色
    const [roleform] = Form.useForm()
    const [addrole, setAddrole] = useState()
    const options = [{
        label: '车辆管理',
        value: '车辆管理'
    },
    {
        label: '系统管理',
        value: '系统管理'
    },
    {
        label: '财务管理',
        value: '财务管理'
    },
    {
        label: '运维管理',
        value: '运维管理'
    }, {
        label: '账号中心',
        value: '账号中心'
    }]
    const roleAdd = () => {
        let roleValue = roleform.getFieldsValue()
        console.log(roleValue);
        systemApi.roleAdd(roleValue).then((res) => {
            console.log(res);
            if (res.code === 200) {
                setAddrole(false)
                Message.success('添加成功')
            }
        })
    }

    // console.log(editvalue);
    const formItemLayout = {
        labelCol: {
            span: 2,
        },
        wrapperCol: {
            span: 26,
        },
    };

    // const bb = (a) => {
    //     console.log(a);
    // }
    return <div style={{ height: '100%', backgroundColor: 'white', textAlign: 'left' }}>
        <p>权限管理</p>
        <div style={{ display: 'flex' }}>
            <div style={{ width: '25%', height: '100%' }}>
                <Input.Search
                    onSearch={querry}
                    style={{
                        margin: '10px',
                        maxWidth: 280,
                    }}
                    onChange={(value) => setInputValue(value)}
                />
                <Tree onSelect={aa}  style={{ marginLeft: '10px' }} defaultSelectedKeys={['0-0-1']} treeData={treeData} showLine='true'></Tree>
            </div>
            <div style={{ width: '77%', height: '100%', marginRight: '10px' }}>
                <Button
                    type='primary'

                    onClick={() => {
                        setAddrole(true)
                    }}
                    style={{ marginRight: 4 }}
                >
                    <IconPlus />添加角色
                </Button>
                {/* 添加人员 */}
                <Button
                    type='primary'

                    onClick={() => {
                        setaddVisible(true)
                    }}
                    style={{ margin: 12 }}
                >
                    <IconPlus />添加人员
                </Button>
                <Button
                    type='primary'

                    onClick={() => {
                        dataShow()
                       
                    }}
                    style={{ marginRight: 4 }}
                >
                  重置
                </Button>
                <Table loading={loading}
                    rowKey={(record) => record.userId}
                    data={data}

                    pagination={{
                        pageSize: 4, sizeCanChange: true,
                        showTotal: (total, range) => `共 ${total} 条 第 ${range[1] / 4} / ${Math.ceil(total / 4)} 页`,
                    }}
                    // onChange={onChangeTable}

                    columns={columns}
                    className='table-demo-editable-cell'
                />

                {/* 修改 */}
                <Modal
                    title='修改'
                    visible={visible}
                    onOk={modifyBtn}
                    onCancel={() => setVisible(false)}
                >
                    <Form
                        {...formItemLayout}
                        form={form}
                        labelCol={{
                            style: { flexBasis: 120 },
                        }}
                        wrapperCol={{
                            style: { flexBasis: 'calc(100% - 120px)' },
                        }}

                    >
                        <FormItem label='序号' field='userId' disabled>
                            <Input placeholder='' autoComplete="off" />
                        </FormItem>
                        <FormItem label='姓名' field='userName' >
                            <Input placeholder='' autoComplete="off" />
                        </FormItem>
                        <FormItem label='所属角色' field='roleName' >
                            <Select onFocus={roleDown} options={roleValue} />
                        </FormItem>
                        <FormItem label='手机号' field='userPhone' >
                            <Input placeholder='' autoComplete="off" maxLength='11' />
                        </FormItem>
                        <FormItem label='电子邮箱' field='userMail' >
                            <Input placeholder='' autoComplete="off" />
                        </FormItem>

                    </Form>
                </Modal>
                {/* 增加 */}
                <Modal
                    title='新增人员'
                    visible={addVisible}
                    onOk={addBox}
                    onCancel={() => setaddVisible(false)}
                >
                    <Form
                        {...formItemLayout}
                        form={formAdd}
                        labelCol={{
                            style: { flexBasis: 120 },
                        }}
                        wrapperCol={{
                            style: { flexBasis: 'calc(100% - 120px)' },
                        }}
                    >

                        <FormItem label='姓名' field='userName' >
                            <Input placeholder='' />
                        </FormItem>


                        <FormItem label='手机号码' field='userPhone' >
                            <Input placeholder='' autoComplete="off" maxLength='11' />
                        </FormItem>
                        <FormItem label='登录密码' field='userPassword'>
                            <Input.Password defaultValue='password' style={{ width: 350 }} />
                        </FormItem>
                        <FormItem label='电子邮箱' field='userMail' >
                            <Input placeholder='' autoComplete="off" />
                        </FormItem>
                        <FormItem label='详细地址' field='userLocation' >
                            <Input placeholder='' autoComplete="off" />
                        </FormItem>
                        <FormItem label='所属角色' field='userRole' >
                            <Select onFocus={roleDown} options={roleValue} />
                        </FormItem>


                    </Form>
                </Modal>
                {/* 添加角色 */}
                <Modal
                    title='添加角色'
                    visible={addrole}
                    onOk={roleAdd}

                    onCancel={() => setAddrole(false)}
                >
                    <Form
                        {...formItemLayout}
                        form={roleform}
                        labelCol={{
                            style: { flexBasis: 90 },
                        }}
                        wrapperCol={{
                            style: { flexBasis: 'calc(100% - 90px)' },
                        }}
                    >
                        <FormItem label='角色名称' field='roleName' required rules={[{ required: true }]}>
                            <Input placeholder='' />
                        </FormItem>
                        <FormItem label='角色权限' field='permissions'>
                            <CheckboxGroup
                                options={options}

                                style={{ display: 'block', marginBottom: 20 }}
                            />
                        </FormItem>

                    </Form>
                </Modal>

            </div>
        </div>

    </div>
}
export default Power